package com.wenwei.net;



import com.orhanobut.logger.Logger;
import com.wenwei.bean.ALiInfoBean;
import com.wenwei.bean.AllCouponBean;
import com.wenwei.bean.CityBean;
import com.wenwei.bean.ConfigBean;
import com.wenwei.bean.HaveSubscriberBean;
import com.wenwei.bean.HisPointBean;
import com.wenwei.bean.LoginBean;
import com.wenwei.bean.LookSuBean;
import com.wenwei.bean.MessageListBean;
import com.wenwei.bean.OrderInfoBean;
import com.wenwei.bean.ParkBean;
import com.wenwei.bean.ParkListBean;
import com.wenwei.bean.ParkingHistoryBean;
import com.wenwei.bean.RechargeBalanceBean;
import com.wenwei.bean.RechargeConfigBean;
import com.wenwei.bean.RegisterBean;
import com.wenwei.bean.SubscriberSuccBean;
import com.wenwei.bean.ThreadLoginBean;
import com.wenwei.bean.UserCouponBean;
import com.wenwei.bean.UserInfoBean;
import com.wenwei.bean.UserOrderEndBean;
import com.wenwei.bean.UserOrderingBean;
import com.wenwei.bean.UserParkBean;
import com.wenwei.bean.WalletHisBean;
import com.wenwei.bean.WeChatPayConfigBean;
import com.wenwei.parking.BaseApplication;
import com.wenwei.parking.Constant;
import com.wenwei.utils.UserStringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.functions.Func1;

/**
 * Created by Administrator on 2016/7/5.
 *
  * 对Retrofit 请求过程进行封装
 */
public class ApiManager {
    public static final int DEFAULT_TIMEOUT = 10;//设置默认超时时间
    private Retrofit retrofit ;
    private ApiInterface mApiService;
    /**
     * 构造方法私有
     */
    private ApiManager(){
        //手动创建一个OkHttpClient并设置超时时间
        OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();
        httpClientBuilder.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
        httpClientBuilder.addNetworkInterceptor(new LogInterceptor());
        httpClientBuilder.addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request()
                        .newBuilder()
                        .addHeader("Content-Type", "application/json")
                        .addHeader("Authorization", UserStringUtils.getUserToken(BaseApplication.getAppContext()))
                        .build();
                return chain.proceed(request);
            }
        });
        //Retrofit的一些配置
        retrofit = new Retrofit.Builder()
                .client(httpClientBuilder.build())//配置okHttp
                .addConverterFactory(GsonConverterFactory.create())//配置CallModel可以使用Gson直接创建Bean
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())//配置ApiService请求可以使用RxJava
                .baseUrl(Constant.BASE_URL)//配置服务器地址
                .build();//创建

        mApiService = retrofit.create(ApiInterface.class);//创建API请求接口
    }

    private static class SingletonHolder{
        private static final ApiManager INSTANCE = new ApiManager();
    }

    public static ApiManager getInstance(){
        return SingletonHolder.INSTANCE;
    }


    private class HttpResultFunc<T> implements Func1<ApiResultBean<T>, T> {
        @Override
        public T call(ApiResultBean<T> httpResult) {
            if (httpResult.getCode() != 200) {
                throw new ApiException(httpResult.getMessage());
            }
            return httpResult.getData();
        }
    }


    //注册验证码
    public void getRegisterSmsCode(BaseSubscriber subscriber,String phone){
        mApiService.getRegisterSmsCode(phone)
                .map(new HttpResultFunc<Object>())
                .compose(TransformUtils.defaultSchedulers())
                .subscribe(subscriber);
    }

    //用户注册
    public void userRegister(BaseSubscriber subscriber,String bodyJs){
        mApiService.userRegister(getBody(bodyJs))
                .map(new HttpResultFunc<RegisterBean>())
                .compose(TransformUtils.<RegisterBean>defaultSchedulers())
                .subscribe(subscriber);
    }

    //用户登录
    public void userLogin(BaseSubscriber subscriber, String userName, String password, String regId) {
        mApiService.userLogin(userName, password, regId, "android")
                .map(new HttpResultFunc<LoginBean>())
                .compose(TransformUtils.<LoginBean>defaultSchedulers())
                .subscribe(subscriber);
    }

    //忘记密码-获取验证码
    public void getForgetSmsCode(BaseSubscriber subscriber,String phone){
        mApiService.getForgetSmsCode(phone)
                .map(new HttpResultFunc<Object>())
                .compose(TransformUtils.defaultSchedulers())
                .subscribe(subscriber);
    }

    //重置密码
    public void userReSetPassWord(BaseSubscriber subscriber,String bodyJs){
        mApiService.userReSetPassWord(getBody(bodyJs))
                .map(new HttpResultFunc<RegisterBean>())
                .compose(TransformUtils.<RegisterBean>defaultSchedulers())
                .subscribe(subscriber);
    }

    //获取用户资料
    public void getUserInfo(BaseSubscriber subscriber,int userId){
        mApiService.getUserInfo(userId)
                .map(new HttpResultFunc<UserInfoBean>())
                .compose(TransformUtils.<UserInfoBean>defaultSchedulers())
                .subscribe(subscriber);
    }

    //修改用户资料
    public void updateUserProfile(BaseSubscriber subscriber,String bodyJs){
        mApiService.updateUserPofile(getBody(bodyJs))
                .map(new HttpResultFunc<Object>())
                .compose(TransformUtils.defaultSchedulers())
                .subscribe(subscriber);
    }

    //停车记录
    public void getParkHistory(BaseSubscriber sb,int userId,int page){
        mApiService.getParkHistory(userId,page)
                .map(new Func1<ParkingHistoryBean, ParkingHistoryBean>() {
                    @Override
                    public ParkingHistoryBean call(ParkingHistoryBean parkingHistoryBean) {
                        if(parkingHistoryBean.getCode()!=200){
                            throw new ApiException(parkingHistoryBean.getMessage());
                        }
                        return parkingHistoryBean;
                    }
                })
                .compose(TransformUtils.<ParkingHistoryBean>defaultSchedulers())
                .subscribe(sb);
    }

    //可开金额
    public void getUsableInvoiceAmount(BaseSubscriber sb,int userId){
        mApiService.getUsableInvoiceAmount(userId)
                .map(new HttpResultFunc<Double>())
                .compose(TransformUtils.<Double>defaultSchedulers())
                .subscribe(sb);
    }

   //索要发票
    public void addInvoice(BaseSubscriber sb,String bodyJs){
        mApiService.addInvoice(getBody(bodyJs))
                .map(new HttpResultFunc<Object>())
                .compose(TransformUtils.defaultSchedulers())
                .subscribe(sb);
    }

    //用户优惠券
    public void getUserCoupon(BaseSubscriber sb,int userId){
        mApiService.getUserCoupon(userId)
                .map(new HttpResultFunc<ArrayList<UserCouponBean>>())
                .compose(TransformUtils.<ArrayList<UserCouponBean>>defaultSchedulers())
                .subscribe(sb);
    }

    //优惠券列表
    public void getCoupon(BaseSubscriber sb,int userId){
        mApiService.getCoupon(userId)
                .map(new HttpResultFunc<ArrayList<AllCouponBean>>())
                .compose(TransformUtils.<ArrayList<AllCouponBean>>defaultSchedulers())
                .subscribe(sb);
    }

    //领取优惠券
    public void addUserCoupon(BaseSubscriber sb,String bodyJs){
        mApiService.addUserCoupon(getBody(bodyJs))
                .map(new HttpResultFunc<Object>())
                .compose(TransformUtils.defaultSchedulers())
                .subscribe(sb);
    }

    //钱包流水
    public void getWalletLog(BaseSubscriber sb,int userId,int page){
        mApiService.getWalletLog(userId,page)
                .map(new Func1<WalletHisBean, WalletHisBean>() {
                    @Override
                    public WalletHisBean call(WalletHisBean walletHisBean) {
                        if(walletHisBean.getCode()!=200){
                            throw new ApiException(walletHisBean.getMessage());
                        }
                        return walletHisBean;
                    }
                })
                .compose(TransformUtils.<WalletHisBean>defaultSchedulers())
                .subscribe(sb);
    }

    public void rechargeConfig(BaseSubscriber sb){
        mApiService.rechargeConfig()
                .map(new HttpResultFunc<ArrayList<RechargeConfigBean>>())
                .compose(TransformUtils.<ArrayList<RechargeConfigBean>>defaultSchedulers())
                .subscribe(sb);
    }

    public void recharges (BaseSubscriber sb,String bodyJs){
        mApiService.recharges(getBody(bodyJs))
                .map(new HttpResultFunc<WeChatPayConfigBean>())
                .compose(TransformUtils.<WeChatPayConfigBean>defaultSchedulers())
                .subscribe(sb);
    }

    public void rechargesAli (BaseSubscriber sb,String bodyJs){
        mApiService.rechargesAli(getBody(bodyJs))
                .map(new HttpResultFunc<String>())
                .compose(TransformUtils.<String>defaultSchedulers())
                .subscribe(sb);
    }

    public void wxPayConfig(BaseSubscriber subscriber, String orderNum) {
        mApiService.wxPayConfig(orderNum)
                .map(new HttpResultFunc<WeChatPayConfigBean>())
                .compose(TransformUtils.<WeChatPayConfigBean>defaultSchedulers())
                .subscribe(subscriber);
    }

    public void alipayConfig(BaseSubscriber subscriber, String orderNum) {
        mApiService.alipayConfig(orderNum)
                .map(new HttpResultFunc<String>())
                .compose(TransformUtils.<String>defaultSchedulers())
                .subscribe(subscriber);
    }

    public void getHistoryParkAddr(BaseSubscriber sb,int userId){
        mApiService.getHistoryParkAddr(userId)
                .map(new HttpResultFunc<ArrayList<HisPointBean>>())
                .compose(TransformUtils.<ArrayList<HisPointBean>>defaultSchedulers())
                .subscribe(sb);
    }

    public void getMessageList(BaseSubscriber subscriber,int page,int size) {
        mApiService.getMessageList(page, size)
                .map(new Func1<MessageListBean, MessageListBean>() {
                    @Override
                    public MessageListBean call(MessageListBean messageListBean) {
                        if(messageListBean.getCode()!=200){
                            throw new ApiException(messageListBean.getMessage());
                        }
                        return messageListBean;
                    }
                })
                .compose(TransformUtils.<MessageListBean>defaultSchedulers())
                .subscribe(subscriber);
    }

    public void openSubscribeParkCar(BaseSubscriber sb,int id){
        mApiService.openSubscribeParkCar(id)
                .map(new HttpResultFunc<UserOrderingBean>())
                .compose(TransformUtils.<UserOrderingBean>defaultSchedulers())
                .subscribe(sb);
    }

    //开锁生成订单
    public void addOrder(BaseSubscriber sb,String bodyJs){
        mApiService.addOrder(getBody(bodyJs))
                .map(new HttpResultFunc<Object>())
                .compose(TransformUtils.defaultSchedulers())
                .subscribe(sb);
    }

   //预约订单
    public void addSubscribeOrder(BaseSubscriber sb,String bodyJs){
        Logger.d("params:"+bodyJs);
        mApiService.addSubscribeOrder(getBody(bodyJs))
                .map(new HttpResultFunc<SubscriberSuccBean>())
                .compose(TransformUtils.<SubscriberSuccBean>defaultSchedulers())
                .subscribe(sb);
    }

    //取消预约订单
    public void cancelSubById(BaseSubscriber sb,int orderId){
        mApiService.cancelSubById(orderId)
                .map(new HttpResultFunc<Object>())
                .compose(TransformUtils.defaultSchedulers())
                .subscribe(sb);
    }

    //查询用户已有预约订单
    public void getUserExistSubByUserId(BaseSubscriber sb,int userId){
        mApiService.getUserExistSubByUserId(userId)
                .map(new HttpResultFunc<HaveSubscriberBean>())
                .compose(TransformUtils.<HaveSubscriberBean>defaultSchedulers())
                .subscribe(sb);
    }

    //订单结束计费
    public void endCharge(BaseSubscriber sb, String bodyJs ){
        mApiService.endCharge(getBody(bodyJs))
                .map(new HttpResultFunc<UserOrderEndBean>())
                .compose(TransformUtils.<UserOrderEndBean>defaultSchedulers())
                .subscribe(sb);
    }

    //查询用户进行中的订单
    public void getOnGoingOrder(BaseSubscriber sb ,int userId){
        mApiService.getOnGoingOrder(userId)
                .map(new HttpResultFunc<UserOrderingBean>())
                .compose(TransformUtils.<UserOrderingBean>defaultSchedulers())
                .subscribe(sb);
    }

    //订单支付
    public void payOrder(BaseSubscriber sb,String bodyJs){
        try{
            mApiService.payOrder(getBody(bodyJs))
                    .map(new HttpResultFunc<WeChatPayConfigBean>())
                    .compose(TransformUtils.<WeChatPayConfigBean>defaultSchedulers())
                    .subscribe(sb);
        }catch (Exception e){
            Logger.d(e.toString());
        }

    }

    //订单支付
    public void payOrderAli(BaseSubscriber sb,String bodyJs){
        try{
            mApiService.payOrderAli(getBody(bodyJs))
                    .map(new HttpResultFunc<String>())
                    .compose(TransformUtils.<String>defaultSchedulers())
                    .subscribe(sb);
        }catch (Exception e){
            Logger.d(e.toString());
        }

    }

    //订单支付
    public void payOrderYu(BaseSubscriber sb,String bodyJs){
        try{
            mApiService.payOrderYu(getBody(bodyJs))
                    .map(new HttpResultFunc<Object>())
                    .compose(TransformUtils.<Object>defaultSchedulers())
                    .subscribe(sb);
        }catch (Exception e){
            Logger.d(e.toString());
        }

    }

    //获取停车场数据
    public void getCityAndPark(BaseSubscriber sb){
        mApiService.getCityAndPark()
                .map(new Func1<CityBean, CityBean>() {
                    @Override
                    public CityBean call(CityBean cityBean) {
                        if(cityBean.getCode() != 200){
                            throw new ApiException(cityBean.getMessage());
                        }
                        return cityBean;
                    }
                })
                .compose(TransformUtils.<CityBean>defaultSchedulers())
                .subscribe(sb);
    }

    //获取停车位
    public void getParkCar4user(BaseSubscriber sb,String lng,String lat){
        mApiService.getParkCar4user(lng,lat)
                .map(new HttpResultFunc<ArrayList<ParkBean>>())
                .compose(TransformUtils.<ArrayList<ParkBean>>defaultSchedulers())
                .subscribe(sb);
    }

    public void getOrderInfo(BaseSubscriber sb,int orderId){
        mApiService.getOrderInfo(orderId)
                .map(new HttpResultFunc<OrderInfoBean>())
                .compose(TransformUtils.<OrderInfoBean>defaultSchedulers())
                .subscribe(sb);
    }

    public void getParkList(BaseSubscriber sb,int userId,int parkId,int page){
        mApiService.getParkList(userId,parkId,page)
                .map(new Func1<ParkListBean, ParkListBean>() {
                    @Override
                    public ParkListBean call(ParkListBean parkListBean) {
                        if(parkListBean.getCode()!=200){
                            throw new ApiException(parkListBean.getMessage());
                        }
                        return parkListBean;
                    }
                })
                .compose(TransformUtils.<ParkListBean>defaultSchedulers())
                .subscribe(sb);
    }

    public void operatePark(BaseSubscriber sb,int parkId){
        mApiService.operatePark(parkId)
                .map(new HttpResultFunc<Object>())
                .compose(TransformUtils.defaultSchedulers())
                .subscribe(sb);
    }

    public void getUserAdmin(BaseSubscriber sb,int userId){
        mApiService.getUserAdmin(userId)
                .map(new HttpResultFunc<ArrayList<UserParkBean>>())
                .compose(TransformUtils.<ArrayList<UserParkBean>>defaultSchedulers())
                .subscribe(sb);

    }

    public void addAllege(BaseSubscriber sb,String bodyJs){
        mApiService.addAllege(getBody(bodyJs))
                .map(new HttpResultFunc<Object>())
                .compose(TransformUtils.defaultSchedulers())
                .subscribe(sb);
    }

    public void getAllegeByOrderId(BaseSubscriber sb,int orderId){
        mApiService.getAllegeByOrderId(orderId)
                .map(new HttpResultFunc<LookSuBean>())
                .compose(TransformUtils.<LookSuBean>defaultSchedulers())
                .subscribe(sb);
    }

    public void getConfig(BaseSubscriber sb){
        mApiService.getConfig()
                .map(new HttpResultFunc<ConfigBean>())
                .compose(TransformUtils.<ConfigBean>defaultSchedulers())
                .subscribe(sb);
    }

    public void threadLogin(BaseSubscriber sb,String threeT){
        mApiService.threadLogin(threeT)
                .map(new HttpResultFunc<LoginBean>())
                .compose(TransformUtils.<LoginBean>defaultSchedulers())
                .subscribe(sb);
    }

    public void getALiLoginConfig(BaseSubscriber sb){
        mApiService.getALiLoginConfig()
                .map(new HttpResultFunc<String>())
                .compose(TransformUtils.<String>defaultSchedulers())
                .subscribe(sb);
    }

    public void bindInfo(BaseSubscriber sb,String token,String phone,String pw,String code,
                         String nikename,String avator,String regId,String platform){
        mApiService.bindInfo(token,phone,pw,code,nikename,avator,regId,platform)
                .map(new HttpResultFunc<Object>())
                .compose(TransformUtils.defaultSchedulers())
                .subscribe(sb);
    }

    public void getAuthInfo(BaseSubscriber sb,String id){
        mApiService.getAuthInfo(id)
                .map(new HttpResultFunc<ALiInfoBean>())
                .compose(TransformUtils.<ALiInfoBean>defaultSchedulers())
                .subscribe(sb);
    }

    public void addOpinion(BaseSubscriber sb,String bodyJs){
        mApiService.addOpinion(getBody(bodyJs))
                .map(new HttpResultFunc<Object>())
                .compose(TransformUtils.defaultSchedulers())
                .subscribe(sb);
    }

    private RequestBody getBody(String s){
        return RequestBody.create(MediaType.parse("application/json;charset=utf-8"),s);
    }


}
